<template>
	<div class="v--upload-file-list">
		<!-- <div :class="['v-upload-dragger', { disabled: !couldUpload }]" ref="draggerDom" @click="openPlus">
			<UploadFilled class="v-upload-icon"></UploadFilled>
			<div class="v-upload-text"><span>点击上传</span></div>
			<span style="color: #9da0a5">最多上传1个文件</span>
			<input
				v-if="!plus"
				v-show="couldUpload"
				class="v-upload-input"
				:accept="accept"
				type="file"
				ref="uploadInput"
				@change="onUpload"
			/>
		</div> -->
		<v-plus v-model="plusVisible" :max="max" type="file" :accept="accept" v-model:file-list="fileList"></v-plus>
		<vue-draggable-next v-model="fileList">
			<transition-group name="v--upload-file">
				<div class="v-upload-item" v-for="(item, index) in fileList" :key="item.url" :title="item.name">
					<Document style="color: #9da0a5; width: 15px; height: 15px; flex: none; margin-right: 5px" />
					<div class="name">{{ item.name }}</div>
					<Close v-show="!disabled" class="v-upload-icon" @click="onRemove(index)" />
				</div>
			</transition-group>
		</vue-draggable-next>
	</div>
</template>
<script setup>
import { VueDraggableNext } from "vue-draggable-next"
import useDrop from "../modules/useDrop"
import { useUpload } from "../modules/useUpload"
import vPlus from "./plus.vue"

const props = defineProps({
	modelValue: {
		type: Array,
		default: () => [],
	},
	max: {
		type: [Number, String],
		default: -1,
	},
	accept: {
		type: String,
		default: "",
	},
	disabled: {
		type: Boolean,
		default: false,
	},
	plus: {
		type: Boolean,
		default: true,
	},
})
const emits = defineEmits(["update:modelValue", "on-success", "on-remove"])

const uploadInput = shallowRef()
const draggerDom = shallowRef()

const couldUpload = computed(() => {
	if (props.disabled) {
		return false
	}
	if (props.max === -1) {
		return true
	}
	return props.modelValue.length < props.max
})
const fileList = computed({
	get() {
		return props.modelValue
	},
	set(value) {
		emits("update:modelValue", value)
	},
})

const { httpRequest } = useUpload(uploadInput)
useDrop(draggerDom, httpRequest, couldUpload, result => {
	fileList.value = fileList.value.concat([...result])
	emits("on-success", result)
})

async function onUpload() {
	if (!couldUpload.value) {
		throw new Error("禁止上传")
	}
	const result = await httpRequest()

	fileList.value = fileList.value.concat([...result])
	emits("on-success", result)
	return result
}
function onRemove(index) {
	const list = fileList.value
	list.splice(index, 1)
	fileList.value = list
	emits("on-remove", { index, list })
}

const plusVisible = shallowRef(false)
function openPlus() {
	if (!couldUpload.value || !props.plus) {
		return
	}
	plusVisible.value = true
}
</script>

<style lang="scss" scoped></style>
